import { NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { verifyPassword } from "@/lib/auth/password"
import { signJwtToken } from "@/lib/auth/jwt"
import { hashPassword } from "@/lib/auth/password"
import { verifyJwtToken } from "@/lib/auth/jwt"

// 日志函数
function log(message: string, data?: any) {
  const timestamp = new Date().toISOString()
  console.log(`[${timestamp}] [AUTH] ${message}`, data ? JSON.stringify(data) : '')
}

// 登录API
export async function POST(req: Request) {
  try {
    log('登录请求开始')
    const { email, password } = await req.json()
    
    // 验证请求数据
    if (!email || !password) {
      log('登录失败: 邮箱或密码为空', { email })
      return NextResponse.json(
        {
          success: false,
          error: "邮箱和密码不能为空",
        },
        { status: 400 }
      )
    }
    
    log('正在验证用户', { email })
    
    // 查找用户
    const user = await prisma.user.findUnique({
      where: { email }
    })
    
    // 用户不存在
    if (!user) {
      log('登录失败: 用户不存在', { email })
      return NextResponse.json(
        {
          success: false,
          error: "该邮箱未注册或密码不正确",
        },
        { status: 401 }
      )
    }
    
    // 验证密码
    const isPasswordValid = await verifyPassword(password, user.password)
    
    if (!isPasswordValid) {
      log('登录失败: 密码错误', { email })
      return NextResponse.json(
        {
          success: false,
          error: "邮箱或密码不正确",
        },
        { status: 401 }
      )
    }
    
    log('密码验证成功，正在生成令牌', { userId: user.id })
    
    // 生成JWT令牌
    const token = signJwtToken({
      userId: user.id,
      email: user.email,
      name: user.name
    })
    
    log('登录成功', { userId: user.id, email: user.email })
    
    // 返回用户信息和令牌
    return NextResponse.json({
      success: true,
      user: {
        id: user.id,
        name: user.name,
        email: user.email
      },
      token
    })
    
  } catch (error) {
    console.error("Auth API Error:", error)
    log('登录过程中发生服务器错误', { error })
    return NextResponse.json(
      {
        success: false,
        error: "登录失败，服务器出现问题",
      },
      { status: 500 }
    )
  }
}

// 注册API
export async function PUT(req: Request) {
  try {
    log('注册请求开始')
    const { name, email, password } = await req.json()
    
    // 验证请求数据
    if (!name || !email || !password) {
      log('注册失败: 缺少必要字段', { name, email })
      return NextResponse.json(
        {
          success: false,
          error: "用户名、邮箱和密码都是必填项",
        },
        { status: 400 }
      )
    }
    
    log('检查邮箱是否已存在', { email })
    
    // 检查邮箱是否已存在
    const existingUser = await prisma.user.findUnique({
      where: { email }
    })
    
    if (existingUser) {
      log('注册失败: 邮箱已存在', { email })
      return NextResponse.json(
        {
          success: false,
          error: "该邮箱已被注册，请直接登录或使用其他邮箱",
        },
        { status: 400 }
      )
    }
    
    log('开始加密密码')
    
    // 加密密码
    const hashedPassword = await hashPassword(password)
    
    log('创建新用户', { name, email })
    
    // 创建新用户
    const newUser = await prisma.user.create({
      data: {
        name,
        email,
        password: hashedPassword
      }
    })
    
    log('用户注册成功', { userId: newUser.id, email })
    
    return NextResponse.json({
      success: true,
      message: "注册成功，请使用新账号登录",
      userId: newUser.id
    })
    
  } catch (error) {
    console.error("Register API Error:", error)
    log('注册过程中发生服务器错误', { error })
    return NextResponse.json(
      {
        success: false,
        error: "注册失败，服务器出现问题",
      },
      { status: 500 }
    )
  }
}

// 获取当前用户信息API
export async function GET(req: Request) {
  try {
    // 从请求头中获取令牌
    const authHeader = req.headers.get('authorization')
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json(
        {
          success: false,
          error: "未授权访问",
        },
        { status: 401 }
      )
    }
    
    const token = authHeader.split(' ')[1]
    
    // 验证令牌
    const payload = verifyJwtToken(token)
    
    if (!payload) {
      return NextResponse.json(
        {
          success: false,
          error: "无效的令牌",
        },
        { status: 401 }
      )
    }
    
    // 查找用户
    const user = await prisma.user.findUnique({
      where: { id: payload.userId }
    })
    
    if (!user) {
      return NextResponse.json(
        {
          success: false,
          error: "用户不存在",
        },
        { status: 404 }
      )
    }
    
    // 返回用户信息
    return NextResponse.json({
      success: true,
      user: {
        id: user.id,
        name: user.name,
        email: user.email
      }
    })
    
  } catch (error) {
    console.error("Get User API Error:", error)
    return NextResponse.json(
      {
        success: false,
        error: "获取用户信息失败",
      },
      { status: 500 }
    )
  }
} 